var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../bd.js')
var router = express.Router()

// 获取数据
router.get("/getSiteList", async function (req, res) {
    let sql = ` select * from  site order by id desc `
    const r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

// 获取收货地址
router.get('/getSite', async function (req, res) {
    let {
        uid,
        id,
        priority
    } = req.query
    //通过用户或者小程序uid获取
    var sql = `select * from site where uid='${uid}' order by id desc `
    //通过id获取收货地址
    if (id) {
        var sql = `select * from site where id='${id}' `
    }
    //获取默认收货地址
    if (priority) {
        var sql = `select * from site where uid='${uid}' and priority='${priority}' `
    }
    const r = await db.doSQL(sql)
    res.send(db.postInFo(r))
})

//删除收货地址
router.get('/deleteSite', async function (req, res) {
    let {
        id
    } = req.query
    var sql = `delete from site where id in (${id})`
    const r = await db.doSQL(sql);
    res.send(db.delText(r))
})

//新增收货地址  修改收货地址
router.post('/addSite', urlencodedParser, async function (req, res) {
    var {
        id, //是否有id 判断是新增还是修改
        name, //姓名
        site, //地址
        Detailed, //详细地址
        uid, //用户的id或者小程序的openid
        nickName = "良人", //网名
        coll
    } = req.body
    var sql = `insert into site (name,site,Detailed,uid,nickName,coll) values ('${name}','${site}','${Detailed}','${uid}','${nickName}','${coll}')`
    if (id) {
        var sql = `update site set name='${name}',site='${site}',Detailed='${Detailed}',uid='${uid}',nickName='${nickName}',coll='${coll}' where id in (${id}) `
    }
    const r = await db.doSQL(sql);
    res.send(db.postText(r))
})

//修改默认收货地址
router.post('/updateSite', urlencodedParser, async function (req, res) {
    var {
        oldId,//修改为不是默认收货地址的id
        newId//修改为默认收货地址的id
    } = req.body
    var sql1 = `update site set priority=0 where id = '${oldId}' `
    var sql2 = `update site set priority=1 where id = '${newId}' `
    const r = await db.doSQL(sql1);
    const r2 = await db.doSQL(sql2);
    res.send(db.postText(r, r2))
})


module.exports = router;